import tornado.web
from app.models import create_db,drop_db,Students
from utils.db import session
class IndexHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("hello,day2tornado")


class XindexHandler(tornado.web.RequestHandler):
    def get(self):
        #页面渲染
        items = ['苍老师','龙老师','大桥老师','都不认识']
        items2 = ['苍老师','龙老师','大桥老师','都不认识']


        self.render('index.html',items=items,items2=items2)

class DbHandler(tornado.web.RequestHandler):
    def get(self):
        create_db()
        self.write("创建表成功")

class DelHandler(tornado.web.RequestHandler):
    def get(self):
        drop_db()
        self.write("删除表成功")

class AddstuHandler(tornado.web.RequestHandler):
    def post(self):
        # stu = Students()
        # stu.s_name = 'jiangjie'
        # stu.s_age = 18
        # session.add(stu)
        # session.commit()
        # self.write("写入成功")
        stus = []
        for i in range(100):
            stu = Students()
            stu.s_name = 'whkangbazi_%s' % i
            stus.append(stu)
        session.add_all(stus)
        session.commit()
        self.write("新增100条数据成功")

class StuHandler(tornado.web.RequestHandler):
    #数据的查询
    def get(self):
        # stu = session.query(Students).all()
        #stu = session.query(Students).filter(Students.s_name=="whkangbazi_1").all()
        #stu = session.query(Students).filter_by(s_name="whkangbazi_2").all()
        stu = session.query(Students).first()
        print(stu)
        self.write("查询成功")
    #修改部分属性
    def patch(self):
        # # pass第一种方式
        # stu = session.query(Students).filter(Students.s_name=='jiangjiejie').first()
        # stu.s_name = 'jiangjie'
        # session.add(stu)
        # session.commit()
        # self.write("更新数据成功")
        #第二种方式  update()
        session.query(Students).filter(Students.s_name == 'jiangjie').update({'s_name':'jiangjiejie'})
        session.commit()
        self.write("更新数据成功")

    #删除数据
    def delete(self):
        #第一种方式
        # stu = session.query(Students).filter(Students.s_name == 'jiangjiejie').first()
        # if stu:
        #     session.delete(stu)
        #     session.commit()
        #     self.write("删除数据成功")

        #第二种方法
        session.query(Students).filter(Students.s_name == 'whkangbazi_6').delete()
        session.commit()
        self.write("删除数据成功")